package com.ljyh.cygnus.screens

import android.content.Intent
import android.widget.Button
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Link
import androidx.compose.material.icons.outlined.NetworkCell
import androidx.compose.material.icons.outlined.SettingsEthernet
import androidx.compose.material.icons.outlined.Wifi
import androidx.compose.material3.Button
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.ljyh.cygnus.screens.viewmodel.APNViewModel
import com.ljyh.cygnus.screens.viewmodel.DataViewModel
import com.ljyh.cygnus.screens.viewmodel.HotSpotViewModel
import com.ljyh.cygnus.screens.viewmodel.WLANViewModel
import com.ljyh.cygnus.screens.viewmodel.WhitelistViewModel
import com.ljyh.cygnus.serve.DevicePolicyService
import com.ljyh.cygnus.utils.FileUtils
import com.ljyh.cygnus.utils.PolicyManager

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
    wlan: WLANViewModel = hiltViewModel(),
    data: DataViewModel = hiltViewModel(),
    hotSpot: HotSpotViewModel = hiltViewModel(),
    apn: APNViewModel = hiltViewModel(),
    whitelist: WhitelistViewModel = hiltViewModel()
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    val whitelistText = rememberSaveable { mutableStateOf("") }

    val wlanState by wlan.uiState.collectAsState()
    val dataState by data.uiState.collectAsState()
    val hotSpotState by hotSpot.uiState.collectAsState()
    val apnState by apn.uiState.collectAsState()
    apn.setSqlitePath(FileUtils.getSqlite3Path(context)!!)

    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(
                title = { Text("Cygnus", style = MaterialTheme.typography.headlineSmall) },
                colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(3.dp)
                )
            )
        }
    ) { pv ->
        Column(
            Modifier
                .padding(pv)
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
        ) {
            Spacer(Modifier.height(8.dp))

            GroupTitle("硬件模块控制")
            ControlItem(
                icon = Icons.Outlined.Wifi,
                name = "WLAN 控制",
                policies = listOf("禁用", "仅扫描", "不管控"),
                initialSelected = 2,
                onPolicySelected = {
                    when (it) {
                        0 -> {
                            PolicyManager.setWifiPolicy(context, PolicyManager.POLICY_DISABLED)
                            wlan.disableWifi()
                        }
                        1 -> {
                            PolicyManager.setWifiPolicy(context, PolicyManager.POLICY_RESTRICTED)
                            wlan.restrictionWifi()
                        }
                        2 -> {
                            PolicyManager.setWifiPolicy(context, PolicyManager.POLICY_ENABLED)
                            wlan.enableWifi()
                        }
                    }
                }
            )

            ControlItem(
                icon = Icons.Outlined.NetworkCell,
                name = "移动数据网络",
                policies = listOf("强开启", "强关闭", "不管控"),
                initialSelected = 2,
                onPolicySelected = {
                    when (it) {
                        0 -> {
                            PolicyManager.setMobileDataPolicy(context, PolicyManager.POLICY_ENABLED)
                            data.enableData()
                        }
                        1 -> {
                            PolicyManager.setMobileDataPolicy(context, PolicyManager.POLICY_DISABLED)
                            data.disableData()
                        }
                        2 -> {
                            PolicyManager.setMobileDataPolicy(context, PolicyManager.POLICY_RESTRICTED)
                            data.defaultData()
                        }
                    }
                }
            )

            Spacer(Modifier.height(12.dp))
            GroupTitle("终端基本功能控制")
            Spacer(Modifier.height(4.dp))

            ControlItem(
                icon = Icons.Outlined.Link,
                name = "网络共享（热点）",
                policies = listOf("禁用", "受限", "不管控"),
                initialSelected = 2,
                onPolicySelected = {
                    when (it) {
                        0 -> {
                            PolicyManager.setHotspotPolicy(context, PolicyManager.POLICY_DISABLED)
                            // 先开启WIFI，这时候会强制关掉热点
                            wlan.enableWifi()
                            // 再关闭WIFI
                            wlan.disableWifi()
                            // 如果wlan 原来是开启的，则需要重新开启
                            if(PolicyManager.getWifiPolicy(context) == PolicyManager.POLICY_ENABLED){
                                wlan.enableWifi()
                            }
                        }
                        1 -> {
                            PolicyManager.setHotspotPolicy(context, PolicyManager.POLICY_RESTRICTED)
                            hotSpot.restrictionHotSpot()
                        }
                        2 -> {
                            PolicyManager.setHotspotPolicy(context, PolicyManager.POLICY_ENABLED)
                            hotSpot.enableHotSpot()
                        }
                    }
                }
            )

            ControlItem(
                icon = Icons.Outlined.SettingsEthernet,
                name = "APN 控制",
                policies = listOf("禁用", "仅查看", "不管控"),
                initialSelected = 2,
                onPolicySelected = {
                    when (it) {
                        0 -> apn.disableAPN()
                        1 -> apn.restrictionAPN()
                        2 -> apn.enableAPN()
                    }
                }
            )

            Spacer(Modifier.height(12.dp))
            GroupTitle("网络白名单")
            Spacer(Modifier.height(4.dp))
            Row {
                TextField(
                    value = whitelistText.value,
                    onValueChange = {
                        whitelistText.value = it
                    },
                    label = { Text("请输入iptables命令") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 24.dp)
                )


            }

            Spacer(Modifier.height(12.dp))

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp),
                horizontalArrangement = Arrangement.End
            ) {
                Button(onClick = {
                    whitelist.addWhitelist(whitelistText.value)
                }) {
                    Text("添加")
                }
                Button(onClick = {
                    whitelist.clearWhitelist()
                }) {
                    Text("清空")
                }
            }



        }
    }
}


@Composable
fun GroupTitle(text: String) {
    Text(
        text = text,
        style = MaterialTheme.typography.titleSmall,
        color = MaterialTheme.colorScheme.primary,
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 24.dp, vertical = 8.dp)
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ControlItem(
    icon: ImageVector,
    name: String,
    policies: List<String>,
    initialSelected: Int,
    onPolicySelected: (Int) -> Unit
) {
    var selected by rememberSaveable { mutableStateOf(initialSelected) }

    ElevatedCard(
        colors = CardDefaults.elevatedCardColors(
            containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(2.dp)
        ),
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 4.dp)
    ) {
        Row(
            Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                icon,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.primary,
                modifier = Modifier.size(24.dp)
            )
            Spacer(Modifier.width(12.dp))
            Text(
                text = name,
                style = MaterialTheme.typography.bodyLarge,
                modifier = Modifier.weight(1f),
                fontSize = 14.sp
            )

            SingleChoiceSegmentedButtonRow {
                policies.forEachIndexed { index, label ->
                    SegmentedButton(
                        shape = SegmentedButtonDefaults.itemShape(
                            index = index,
                            count = policies.size
                        ),
                        selected = index == selected,
                        onClick = {
                            selected = index
                            onPolicySelected(index)
                        },
                        label = {
                            Text(
                                label,
                                style = MaterialTheme.typography.labelSmall,
                                fontSize = 12.sp
                            )
                        }
                    )
                }
            }
        }
    }
}

@Composable
fun StatusPanel(list: List<Pair<String, Boolean>>) {
    ElevatedCard(
        Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp)
    ) {
        Column(Modifier.padding(16.dp)) {
            Text(
                text = "执行状态",
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(bottom = 8.dp)
            )
            list.forEach { (title, enabled) ->
                Row(
                    Modifier
                        .fillMaxWidth()
                        .padding(vertical = 4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    val color = if (enabled) Color.Green else Color.Gray
                    Box(
                        Modifier
                            .size(12.dp)
                            .clip(CircleShape)
                            .background(color)
                    )
                    Spacer(Modifier.width(8.dp))
                    Text(
                        text = "$title：${if (enabled) "已启用" else "已禁用"}",
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
            }
        }
    }
}